var caryr = {
    lang: 'cn',
    updateI18n: function () {
        var msgObjMap = $.i18n.map;
        for (var msgCls in msgObjMap) {
            if (msgCls.lastIndexOf('msg_plh_') == 0) {
                $('input[placeholder="' + msgCls + '"]').attr('placeholder', $.i18n.prop(msgCls));
            } else {
                var cls = '.' + msgCls;
                $(cls).text($.i18n.prop(msgCls));
            }
        }
    },
    loadI18n: function (callback, async) {
        if (async == false) {

        } else {
            async = true;
        }
        $.i18n.properties({
            name: 'messages',
            path: 'resources/bundle/',
            mode: 'both',
            async: async,
            language: this.lang,
            callback: function () {
                caryr.updateI18n();
                if (callback) {
                    callback();
                }
            }
        });
    },
    changeLanguage: function (lang) {
        this.lang = lang;
        this.loadI18n();
    },
    hideTxt:function(txt,length){
        return txt.length>length?txt.substr(0,length)+"...":txt;
    },
    serverMsg: function (data) {
        var msgId = "";
        if (data) {
            data = $.parseJSON(data);
            msgId = "msg_com_updateMsg_" + data.result;
        } else {  //System error pls try again
            msgId = "msg_com_systemError";
        }
        errMsg = $.i18n.prop(msgId);
        return errMsg;
    },
    /*i18nStr: function () {
        return $.i18n.prop(msgId);
    },*/
    formatDate: function (datetime) {
        var year = datetime.getFullYear();
        var month = datetime.getMonth() + 1 < 10 ? "0" + (datetime.getMonth() + 1) : datetime.getMonth() + 1;
        var date = datetime.getDate() < 10 ? "0" + datetime.getDate() : datetime.getDate();
        var hour = datetime.getHours() < 10 ? "0" + datetime.getHours() : datetime.getHours();
        var minute = datetime.getMinutes() < 10 ? "0" + datetime.getMinutes() : datetime.getMinutes();
        var second = datetime.getSeconds() < 10 ? "0" + datetime.getSeconds() : datetime.getSeconds();
        return year + "-" + month + "-" + date + " " + hour + ":" + minute + ":" + second;
    },
    /*tableSearch: function (table, searchForm, productFilter) {
        var searchValue = "";
        if (productFilter) {
            searchValue = productFilter + ',';
        }
        searchForm.find('input').each(function (i, e) {
            var value = $(e).val();
            if (value == 'isEmpty') {
                value = '';
            }
            if ($(e).val()) {
                searchValue += '"' + $(e).attr('name') + '":"' + value + '",';
            }
        });
        searchForm.find('select').each(function (i, e) {
            var value = $(e).val();
            if (value == 'isEmpty') {
                value = '';
            }
            if ($(e).val()) {
                searchValue += '"' + $(e).attr('name') + '":"' + value + '",';
            }
        });
        searchValue = searchValue.substr(0, searchValue.length - 1);
        console.log(searchValue);
        table.search(searchValue).draw();
    },*/

    attchLogout: function (e) {
        e.on('click', function () {
            swal({
                title: $.i18n.prop("msg_com_confirmLogOut"),
                text: "",
                type: "info",
                showCancelButton: true,
                closeOnConfirm: false,
                confirmButtonText: $.i18n.prop("msg_com_formOK"),
                cancelButtonText: $.i18n.prop("msg_com_formCancel"),
                showLoaderOnConfirm: true
            }, function () {
                $.ajax({
                    type: "GET",
                    url: "./api/user/logout",
                    traditional: true, //参数序列化的传统样式
                    success: function (data) {
                        window.location = 'userLogin';
                    },
                    error: function (XMLHttpRequest, textStatus, errorThrown) {
                    }
                });
            });
        });
    },
    attchChangeLang: function (e, callBack) {
        e.on('click', function () {
            var lang = $(this).attr('data-lang');
            caryr.changeLanguage(lang);
            if (callBack) {
                callBack($(this));
            }

            $.ajax({
                type: "get",
                url: "../erp/change-lang",
                traditional: true, //参数序列化的传统样式
                data: {
                    lang: lang
                },
                success: function (data) {
                },
                error: function (XMLHttpRequest, textStatus, errorThrown) {
                }
            });

        });
    },
    /*createDatetime: function (e) {
        e.datetimepicker({
            autoclose: true,
            isRTL: App.isRTL(),
            format: "yyyy-mm-dd hh:ii:ss",
            pickerPosition: (App.isRTL() ? "bottom-right" : "bottom-left")
        });
    },*/
    collectFormData: function (formId) {
        var data = {};
        $(formId).find('input,select').each(function (i, e) {
            data[$(e).attr('name')] = $(e).val();
        });
        return data;
    },
    /*createTable: function (option) {

        var ajax;
        if (option.ajax && option.ajax.data) {
            ajax = {
                "url": "../erp/json-" + option.objName + "-list",
                "data": option.ajax.data
            }
        } else {
            ajax = {
                "url": "../erp/json-" + option.objName + "-list",
            }
        }

        var buttons;

        if (option.disableBtns) {
            buttons = [];
        } else {
            buttons = [{
                extend: 'collection',
                text: "Export",
                className: ' btn sbold green msg_dt_export',
                buttons: [
                    {extend: 'print', className: 'btn default'},
                    {extend: 'pdf', className: 'btn default'},
                    {extend: 'csv', className: 'btn default'}]

            }];
        }
        var search;
        if (option.search) {
            search = {
                "search": option.search
            };
        } else {
            search = {};
        }

        var pageLength;
        if (option.pageLength) {
            pageLength = option.pageLength;
        } else {
            pageLength = 10;
        }


        var tab = $('#' + option.tableId).DataTable({
            language: {
                "url": "resources/bundle/dataTable_" + option.lang + ".json"
            },
            ajax: ajax,
            processing: true,
            searching: true,
            serverSide: true,
            buttons: buttons,
            search: search,
            responsive: {details: {}},
            lengthMenu: [
                [10, 25, 50, 100, -1],
                [10, 25, 50, 100, "All"] // change per page values here
            ],
            pageLength: pageLength,
            order: [option.order],
            columns: option.columns,
            "dom": "<'row' <'col-md-12'B>><'row'<'col-md-6 col-sm-12'l><'col-md-6 col-sm-12'f>r><'table-scrollable't><'row'<'col-md-5 col-sm-12'i><'col-md-7 col-sm-12'p>>", // horizobtal scrollable datatable
        });

        tab.on('init.dt', function () {
            $('.dataTables_filter').addClass("hidden");//hide dataTable search
            caryr.loadI18n();
        });
        return tab;
    },*/
    attachCopyModalCheckbox: function (formModal) {
        formModal.find("input:checkbox").each(function (i, e) {
            $(this).on('click', function () {
                var textInput = $(this).closest('.form-group').find('input:text');
                if (this.checked) {
                    textInput.val('');
                    textInput.attr('disabled', 'disabled');
                } else {
                    textInput.removeAttr('disabled');
                }
            });
        });
    },
    /********************* Used Task Portlet****************/
    createTaskPortlet: function (option) {
        var taskPortlet = {};
        taskPortlet.model = option.model;
        taskPortlet.portlet = option.portlet;
        taskPortlet.deleteEntity = option.deleteEntity;
        taskPortlet.taskListUl = taskPortlet.portlet.closest('.tasks-widget').find('ul.task-list');
        taskPortlet.templateLi = taskPortlet.taskListUl.find('li.tempalte');
        taskPortlet.onAddTaskItem = option.onAddTaskItem;
        taskPortlet.count = 0;

        $('.scroller').slimScroll({});        //enable scroll

        taskPortlet.portlet.find('.add_task').on('click', function () {
            taskPortlet.addTaskItem({});
        });

        taskPortlet.addTaskItem = function (entity) {
            if (option.beforeAddTaskItem) {
                option.beforeAddTaskItem(entity);
            }
            var newLi = taskPortlet.templateLi.clone();
            newLi.removeClass('hidden').removeClass('tempalte');
            for (var property in entity) {
                var input = newLi.find('input[name="' + property + '"], select[name="' + property + '"]');
                caryr.setInputVal(input, entity[property]);
            }
            if (taskPortlet.onAddTaskItem) {
                taskPortlet.onAddTaskItem(entity, newLi);
            }
            if (entity.hiddenModel) {
                var jsonStr = JSON.stringify(entity.hiddenModel);
                newLi.find('span.hiddenModel').html(jsonStr);
            }
            newLi.attr('data-index', taskPortlet.count);
            taskPortlet.count += 1;
            taskPortlet.taskListUl.append(newLi);
            taskPortlet.attachDeleteEvent();
        };

        taskPortlet.attachDeleteEvent = function () {
            taskPortlet.portlet.find('.delete_task').on('click', function () {
                var li = $(this).closest('li');
                if (taskPortlet.deleteEntity) {
                    taskPortlet.deleteEntity(li);
                } else {
                    li.remove();
                }
            });
        };

        taskPortlet.attachDeleteAllEvent = function () {
            taskPortlet.portlet.find('.delete_task_all').on('click', function () {
                taskPortlet.portlet.find('ul.task-list > li input:checkbox.select_item:checked').each(function () {
                    var li = $(this).closest('li');
                    if (!caryr.hasClass(li, 'list-header') && !caryr.hasClass(li, 'tempalte')) {
                        if (taskPortlet.deleteEntity) {
                            taskPortlet.deleteEntity(li);
                        } else {
                            li.remove();
                        }
                    }
                });
            });
        };
        taskPortlet.attachDeleteAllEvent();

        taskPortlet.refreshData = function (entityList) {
            taskPortlet.clear();
            for (var i = 0; i < entityList.length; i++) {
                var entity = entityList[i];
                taskPortlet.addTaskItem(entity);
            }
        };

        taskPortlet.clear = function () {
            taskPortlet.portlet.find('ul.task-list>li').each(function (i, e) {
                //keep header and template li
                if (i > 1) $(e).remove();
            });
        };

        taskPortlet.collectData = function () {
            var taskList = new Array();
            taskPortlet.taskListUl.find('li').each(function (i, e) {
                if (i > 1) {
                    var sku = {};
                    $(e).find('input, select').each(function (i, f) {
                        var name = $(f).attr('name');
                        var type = $(f).attr('type');
                        if (name) {
                            if (type == 'radio') {
                                sku[name] = $('input[name="' + name + '"]:checked').val();
                            } else if (type == "checkbox") {
                                sku[name] = $(f).is(":checked") ? true : false;
                            } else {
                                sku[name] = $(f).val();
                            }
                        }
                    });
                    var jsonStr = $(e).find('span.hiddenModel').html();
                    if (jsonStr) {
                        sku.hiddenModel = $.parseJSON(jsonStr);
                    }
                    taskList.push(sku);
                }
            });
            return taskList;
        };
        //Attach selectAll
        taskPortlet.portlet.find('.list-header input.select_item[type="checkbox"]').off('click').on('click', function () {
            var that = this;
            taskPortlet.portlet.find('ul.task-list > li input.select_item:checkbox').each(function () {
                if (!caryr.hasClass($(this.closest('li')), 'tempalte')) {//exclude template
                    this.checked = that.checked;
                }
            });
        });

        taskPortlet.editable = function (editable) {
            if (editable) {
                taskPortlet.portlet.find('input,select').prop("disabled", false);
                taskPortlet.portlet.find('a.add_task,a.delete_task_all,a.delete_task').removeClass("hidden");
            } else {
                taskPortlet.portlet.find('input,select').prop("disabled", true);
                taskPortlet.portlet.find('a.add_task,a.delete_task_all,a.delete_task').addClass("hidden");
            }
        }

        if (option.disabled) {
            taskPortlet.editable(!option.disabled);
        }

        if(option.entities){
            taskPortlet.refreshData(option.entities);
        }
        return taskPortlet;
    },
    /********************* Used Form ****************/
    collectEntity: function (rootEle, option) {
        var obj = {};
        rootEle.find('input, select, textarea').each(function (i, e) {
            var input = $(e);
            var value = caryr.getInputVal(input);
            var append = option && option.nonNull && !value ? false : true;
            var name = input.attr('name');
            if (append) {
                if (option && option.isFilter) {
                    var operator = input.attr('data-operator') ? input.attr('data-operator') : "";
                    if (operator == "between") {
                        var index = name.indexOf("from") != -1 ? name.indexOf("from") - 1 : name.indexOf("to") - 1;
                        name = name.substr(0, index);
                    }
                    value = caryr.updateFilterValue(input, obj[name]);
                }
                obj[name] = value;
            }
        });
        return obj;
    },
    updateFilterValue: function (input, valObj) {
        valObj = valObj ? valObj : {};
        var operator = input.attr('data-operator') ? input.attr('data-operator') : "";
        var value = caryr.getInputVal(input);
        var name = input.attr('name');
        if (operator == "between") {
            if (name.indexOf("from") != -1) {
                valObj.from = value;
            } else if (name.indexOf("to") != -1) {
                valObj.to = value;
            }
        } else {
            valObj.value = value;
        }
        valObj.operator = operator;
        return valObj;
    },
    getFormInstatnce: function (formId, option) {
        var caryrForm = {};
        caryrForm.formId = formId;
        caryrForm.form = $('#' + formId);
        caryrForm.afterSaveSuccess = option.afterSaveSuccess;
        caryrForm.afterSaveAndNewSuccess = option.afterSaveAndNewSuccess;
        caryrForm.afterCollectEntityData = option.afterCollectEntityData;
        caryrForm.validateForm = function () {
            var result = caryr.validateForm(caryrForm.form);
            if (option.validateForm) {
                return option.validateForm(result, caryrForm.form);
            }
            return result;
        };
        caryrForm.collectEntityData = function () {
            /*var obj = {};
            caryrForm.form.find('.edit_data').find('input, select, textarea').each(function (i, e) {
                var input = $(e);
                var append = true;
                var type = input.attr('type');
                var name = input.attr('name');
                var value = input.val();
                switch (type) {
                    case 'radio':
                        value = $('input[name="' + name + '"]:checked').val();
                }
                if (append) {
                    obj[name] = value;
                }
            });
            return obj;*/
            return caryr.collectEntity(caryrForm.form.find('.edit_data'));
        };

        caryrForm.submitFormData = function () {
            if (!caryrForm.validateForm || (caryrForm.validateForm && caryrForm.validateForm(caryrForm.form))) {
                App.blockUI();
                /*var entity = caryrForm.collectEntityData(caryrForm.formId);*/
                var entity = caryrForm.collectEntityData();
                if (caryrForm.afterCollectEntityData) {
                    caryrForm.afterCollectEntityData(entity);
                }
                caryr.createOrUpdate({
                    url: option.url,
                    data: entity,
                    success: function (data, action) {
                        caryrForm.afterSaveSuccess(data, action);
                    }
                });
            }
        };
        //TODO:replace #btn_edit_form_save by button.from_save
        //attach save button
        $('#btn_edit_form_save, button.form_save').on('click', function () {
            caryrForm.submitFormData();
        });
        //attach saveAndnew button
        $('#btn_edit_form_save_and_new, button.form_save_and_new').on('click', function () {
            if (!caryrForm.validateForm || (caryrForm.validateForm && caryrForm.validateForm())) {
                App.blockUI();
                /*var entity = caryrForm.collectEntityData(caryrForm.formId);*/
                var entity = caryrForm.collectEntityData();
                if (caryrForm.afterCollectEntityData) {
                    caryrForm.afterCollectEntityData(entity);
                }
                caryr.createOrUpdate({
                    url: option.url,
                    data: entity,
                    success: function (data, action) {
                        caryrForm.afterSaveAndNewSuccess(data, action);
                    }
                });
            }
        });
        //Max length
        var defaultMaxLength = {
            alwaysShow: true,
            warningClass: 'label label-success',
            limitReachedClass: 'label label-danger',
            validate: true
        }
        caryrForm.form.find('input').each(function (i, e) {
            var type = $(e).attr('type');
            var maxLength = $(e).attr('maxLength');
            if (maxLength) {
                $(e).maxlength(defaultMaxLength);
            }
        });
        caryrForm.editable = function (editable) {
            if (!editable) {
                caryrForm.form.find("input,textarea,select").prop("disabled", true);
                $("#btn_edit_form_save, #btn_edit_form_save_and_new").addClass("hidden");
            } else {
                caryrForm.form.find("input,textarea,select").prop("disabled", false);
                $("#btn_edit_form_save, #btn_edit_form_save_and_new").removeClass("hidden");
            }
        }
        if (option.disabled) {
            caryrForm.editable(!option.disabled);
            /*caryrForm.form.find("input,textarea,select").prop("disabled",true);
            $("#btn_edit_form_save, #btn_edit_form_save_and_new").addClass("hidden");*/
        }
        return caryrForm;
    },
    /*********************ErpG used****************/
    createOrUpdate: function (option) {
        var data = JSON.stringify(option.data);
        var url = option.url;
        var type = option.data.id ? 'PUT' : 'POST';

        var success = function (data) {
            App.unblockUI();
            var msgTxt = type == 'POST' ? "msg_api_succ_create" : "msg_api_succ_update";
            swal({
                title: $.i18n.prop(msgTxt),
                text: "",
                type: "success"
            }, function () {
                if (option.success) {
                    success = option.success(data, type);
                }
            });
        };

        var error = function (XMLHttpRequest, textStatus, errorThrown) {
            App.unblockUI();
            var msgTxt = $.i18n.prop("msg_com_systemError");
            swal({
                title: msgTxt,
                text: "",
                type: "error"
            }, function () {

            });
        };

        $.ajax({
            type: type,
            url: url,
            dataType: "json",
            contentType: "application/json; charset=utf-8",
            traditional: true, //参数序列化的传统样式
            data: data,
            success: success,
            error: error
        });
    },
    /*********************ErpG used****************/
    deleteEntity: function (option) {
        var url = option.url + '/' + caryr.ids2UrlParam(option.ids);
        swal({
            title: $.i18n.prop("msg_com_confirmDel"),
            confirmButtonText: $.i18n.prop("msg_com_formOK"),
            cancelButtonText: $.i18n.prop("msg_com_formCancel"),
            text: "",
            type: "info",
            showCancelButton: true,
            closeOnConfirm: false,
            showLoaderOnConfirm: true
        }, function () {
            $.ajax({
                type: "DELETE",
                url: url,
                traditional: true, //参数序列化的传统样式
                data: {
                    ids: option.ids
                },
                success: function (response) {
                    var msgTxt = $.i18n.prop("msg_api_succ_delete");
                    swal({
                        title: msgTxt,
                        text: "",
                        type: "success"
                    }, function () {
                        if (option.success) {
                            option.success(response);
                        }
                    });
                },
                error: function (XMLHttpRequest, textStatus, errorThrown) {
                    var msgTxt = "";
                    if (XMLHttpRequest && XMLHttpRequest.responseJSON) {
                        msgTxt = $.i18n.prop("msg_err_" + XMLHttpRequest.responseJSON.code);
                    }
                    var reg = /^\[.*\]$/;
                    if (reg.test(msgTxt)) {
                        msgTxt = $.i18n.prop("msg_com_systemError");
                    }
                    msgTxt = msgTxt?msgTxt:$.i18n.prop("msg_com_systemError");
                    swal({
                        title: msgTxt,
                        text: "",
                        type: "error"
                    }, function () {
                        if (option.error) {
                            option.error();
                        }
                    });
                }
            });
        });
    },
    /*********************ErpG used****************/
    showTab: function (tabId) {
        var li = $(tabId);
        li.tab('show');
        li.closest('div').find('>.tab-content>.tab-pane').removeClass('active');
        var target = li.find('a').attr('href');
        $(target).addClass('active');
    },
    /*********************ErpG used****************/
    randomStringInt: function (length) {
        var num = Math.random();
        for (var i = 0; i < length + 1; i++) {
            num = num * 10;
        }
        num = "" + num;
        return num.substr(0, length);
    },
    /*********************ErpG used****************/
    updateEntity: function (root, entity) {
        if($.isEmptyObject(entity)){
            //Clear all fields
            var input = root.find('input, select, textarea');
            caryr.setInputVal(input, '');

        }else{
            for (var property in entity) {
                var propertyFilter = '[name="' + property + '"]';
                var input = root.find('input' + propertyFilter + ', select' + propertyFilter + ', textarea' + propertyFilter);
                caryr.setInputVal(input, entity[property]);
            }
        }
    },
    getInputVal: function (input) {
        var type = input.attr('type');
        var name = input.attr('name');
        var value;
        switch (type) {
            case 'radio':
                value = $('input[name="' + name + '"]:checked').val();
                break;
            default:
                value = input.val();
        }
        return value;
    },
    setInputVal: function (input, value) {
        var type = input.attr('type');
        switch (type) {
            case 'radio':
                for (var i = 0; i < input.length; i++) {
                    var radio = $(input[i]);
                    var compareValue = radio.val();
                    if (value == compareValue) {
                        radio.prop('checked', true);
                    } else {
                        radio.prop('checked', false);
                    }
                }
                break;
            default:
                input.val(value);
        }
    },
    /********************* Used Validate Form ****************/
    validateForm: function (form) {
        var result = true;
        form.find('input').each(function (i, e) {
            var required = $(e).attr('data-valid-required') == undefined ? false : true;
            if (required && !$(e).val()) {
                $(e).closest('.form-group').removeClass('has-success');
                $(e).closest('.form-group').addClass('has-error');
                result = false;
            } else {
                $(e).closest('.form-group').removeClass('has-error');
                $(e).closest('.form-group').addClass('has-success');
            }
        });
        if (result) {
            caryr.toggleErrorMessage({show: false});
        } else {
            caryr.toggleErrorMessage({
                show: true,
                title: 'msg_form_err',
                subTitle: 'msg_form_err_detail'
            });
        }
        return result;
    },

    //Deprecated. Replaced by loadData.
    fetchRefList: function (option) {
        var requestData = {draw: 0};
        if (option.requestData) {
            requestData = option.requestData;
        }
        if (option.orderBy) {
            requestData = {
                draw: 0,
                orderBy: option.orderBy
            }
        }
        var async = true;
        if (option.async !== undefined) {
            async = option.async;
        }
        $.ajax({
            url: option.url,
            data: requestData,
            type: 'GET',
            async: async,
            success: function (data) {
                if (data && option.refSelect) {
                    var copyData = data.data;
                    if (option.beforeAppend) {
                        copyData = option.beforeAppend(data.data);
                    }

                    var optionsHtml = caryr.select.getOptionsHtml(copyData, option.textFormat, option.formatCb);
                    for (var i = 0; i < option.refSelect.length; i++) {
                        if (option.replace) {
                            option.refSelect[i].html('');
                        }
                        option.refSelect[i].prepend(optionsHtml);
                        if (option.defaultValue) {
                            option.refSelect[i].val(option.defaultValue);
                        }
                    }
                }
                if (option.callback) {
                    option.callback(data, option.refSelect);
                }
            }
        });
    },
    /*********************ErpG used****************/
    select: {
        refreshOptions: function (data, elements, option) {
            if (data && elements) {
                var optionsHtml = caryr.select.getOptionsHtml(data, option.textFormat, option.formatCb, option.descriptionField, option);
                for (var i = 0; i < elements.length; i++) {
                    if (option.replace) {
                        elements[i].html('');
                    }
                    elements[i].prepend(optionsHtml);
                    if (option.defaultValue) {
                        elements[i].val(option.defaultValue);
                    }
                }
            }
        },
        /* Replace formatCb by formatter for readability*/
        getOptionsHtml: function (data, textFormt, formatCb, descriptionField, option) {
            var html = (option && option.excludeEmpty) ? '' : '<option value="0" selected="selected" ></option>';
            for (var i = 0; i < data.length; i++) {
                if (formatCb) {  //Format callback function
                    html += formatCb(data[i]);
                } else if (option && option.formatter) {
                    html += option.formatter(data[i]);
                }else {
                    var description = '';
                    if (descriptionField) {
                        description = data[i][descriptionField];
                    } else {
                        description = data[i].name;
                    }

                    if (textFormt == '1') {  //"name(id)"
                        html += '<option value="' + data[i].id + '">' + description + '  (' + data[i].id + ')</option>';
                    } else if (textFormt == '2') {  //"name(code)"
                        html += '<option value="' + data[i].id + '">' + description + '  (' + data[i].code + ')</option>';
                    } else {
                        html += '<option value="' + data[i].id + '">' + description + '</option>';
                    }
                }
            }
            return html;
        }
    },
    loadData: function (option) {
        var data = option.data ? option.data : {};
        var async = option.async == false ? false : true;
        $.ajax({
            url: option.url,
            data: data,
            type: 'GET',
            async: async,
            success: function (data) {
                option.callback(data, option.elements, option);
            }, error: function (response) {
                caryr.errorHandler(response,option.error);
            }
        });
    },
    errorHandler: function (response, callback) {
        if (response.responseJSON && response.responseJSON.msgCode) {
            var msgTxt = $.i18n.prop("msg_err_" + response.responseJSON.msgCode);
            msgTxt = msgTxt != "" ? msgTxt : $.i18n.prop("msg_com_systemError");
            swal({
                title: msgTxt,
                text: "",
                type: "error"
            }, function () {
                if (callback) {
                    callback(response);
                }
            });

        } else if (callback) {
            callback(response);
        }
    },
    /********************* Used error Message ****************/
    toggleErrorMessage: function (option) {
        var error = $('#form_error_msg');

        if (option.show) {
            error.removeClass('hidden');
        } else {
            error.addClass('hidden');
        }
        error.find('.msg_err_title').html($.i18n.prop(option.title));
        error.find('.msg_err_subTitle').html($.i18n.prop(option.subTitle));
    },
    /********************* Used check has class ****************/
    hasClass: function (element, className) {
        var clz = element.attr('class');
        return clz.indexOf(className) != -1;
    },
    /********************* Used COPY ENTITY ****************/
    copyEntity: function (source, target) {
        for (var property in source) {
            if (typeof source[property] != "object" && property != "id") {
                target[property] = source[property];
            }
        }
    },

    /********** Used Confirm Dialog *********/
    confirm: function (option) {
        var title = option && option.title ? option.title : "";
        var type = option && option.type ? option.type : "info";
        var confirmButtonText = option && option.confirmButtonText ? option.confirmButtonText : $.i18n.prop("msg_com_formOK");
        var cancelButtonText = option && option.cancelButtonText ? option.cancelButtonText : $.i18n.prop("msg_com_formCancel");
        swal({
            title: title,
            confirmButtonText: confirmButtonText,
            cancelButtonText: cancelButtonText,
            text: "",
            type: type,
            showCancelButton: true,
            closeOnConfirm: false,
            showLoaderOnConfirm: true
        }, function () {
            if (option.onConfirm) {
                option.onConfirm();
            }
        });
    },
    /********** Used Ajax Request *********/
    encodeUrlParam: function (key, value) {
        return encodeURIComponent(key) + '=' + encodeURIComponent(value);
    },
    ajaxReq: function (option) {
        var url = option.url;
        var type = option.type ? option.type : "GET";
        var data = JSON.stringify(option.data);
        App.blockUI({
            boxed: true,
            message: $.i18n.prop("msg_loading")
        });
        $.ajax({
            type: type,
            url: url,
            data: data,
            dataType: "json",
            contentType: "application/json; charset=utf-8",
            traditional: true,
            success: function (response) {
                App.unblockUI();
                var successMsg = $.i18n.prop("msg_api_succ");
                if (option.successMsgRender) {
                    successMsg = option.successMsgRender(response);
                } else if (option.successMsg) {
                    successMsg = option.successMsg;
                }
                if (option.skipMsg == true) {
                    if (option.success) {
                        option.success(response);
                    }
                } else {
                    swal({
                        title: successMsg,
                        text: "",
                        type: "success"
                    }, function () {
                        if (option.success) {
                            option.success(response);
                        }
                    });
                }
            },
            error: function (XMLHttpRequest) {
                App.unblockUI();
                caryr.errorHandler(XMLHttpRequest,option.errorCallback);
            }
        });
    },
    /********************* Used error Message ****************/
    refreshEditForm: function (entity, editable, formId) {
        if (entity != null && jQuery.isEmptyObject(entity)) { //Clear all fields
            $(formId).find('div.edit_data').find('input, select, textarea').each(function (i, e) {
                var inputType = $(e).attr("type");
                if (inputType == "radio") {

                } else if (inputType == "file") {

                } else {
                    $(e).val("");
                }
            });
            $(formId).find('p.form-control-static').each(function (i, e) {
                $(e).html('');
            });
        } else if (entity != null) {
            for (var attr in entity) {
                var value = entity[attr];
                var input = $(formId).find('.edit_data [name="' + attr + '"]');
                var isImg = false;
                //Set value for edit fields
                if (input.size() == 0) {
                    input = $(formId).find('.fileinput.' + attr + ' input[name="' + attr + '_old"]');
                    isImg = true;
                }
                var inputType = input.attr('type');
                if (inputType == 'checkbox') {
                    if (value == true) {
                        input.bootstrapSwitch('state', true);
                    } else {
                        input.bootstrapSwitch('state', false);
                    }
                } else if (inputType == "file") {

                } else if (isImg) {

                } else if (inputType == "radio") {
                    for (var i = 0; i < input.length; i++) {
                        var radio = $(input[i]);
                        var compareValue = radio.val();
                        if (value == compareValue) {
                            radio.prop('checked', true);
                        } else {
                            radio.prop('checked', false);
                        }
                    }
                } else {
                    input.val(value);
                }
                //Display fields
                var displayField = $(formId).find('p.form-control-static[name="' + attr + '"]');
                if (displayField) {
                    displayField.html(value);
                }
            }
        }
    },
    triggerCounterUp: function (e, count) {
        e.attr('data-counter', 'counterup');
        e.attr('data-value', count);
        e.counterUp();
    },
    progressBar: function (e, finish, total) {
        var percent = total != 0 ? Math.floor(finish * 100 / total) : 0;
        e.find('.display .number .progress_number').html(finish); //finish
        e.find('.progress-info .status-number').html(percent + '%');  //percentage
        e.find('.progress .progress-bar').css('width', percent + '%');  //progress bar
        caryr.triggerCounterUp(e.find('.progress-info .status-title i'), total); //total
    },
    msgCode:{
        ENTITY_NOT_FOUND:"ENTITY_NOT_FOUND"
    },
    utils: {
        findFromList: function (list, property, value) {
            var obj = null;
            if (!list || !list.length) {
                return obj;
            }

            for (var i = 0; i < list.length; i++) {
                if (list[i][property] == value) {
                    obj = list[i];
                    break;
                }
            }
            return obj;
        }
    },
    toJson: function (obj) {
        return JSON.stringify(obj);
    },
    ids2UrlParam: function (ids) {
        var urlParam = '';
        for (var i = 0; i < ids.length; i++) {
            if (i != ids.length - 1) {
                urlParam += ids[i] + ",";
            } else {
                urlParam += ids[i];
            }
        }
        return urlParam;
    },
    updateInlineProp: function (rootEle, property, val) {
        rootEle.find('.inline_display[name="' + property + '"]').html(val);
    }
};

/******* Order Function *****/
caryr.order = {
    orderStatusHtml: function (status) {
        var style = "label-default";
        if (status == 10) {
            style = "label-default";
        } else if (status <= 70) {
            style = "label-danger";
        } else if (status >= 90) {
            style = "label-success";
        } else {
            style = "label-warning";
        }
        var msgClass = "msg_order_std_" + status;
        return "<span class='label label-sm " + style + " " + msgClass + "'>" + $.i18n.prop(msgClass) + "</span>";
    }
};
/******* Stock Function *****/
caryr.stock = {
    stockTotoalQuantityHtml: function (count) {
        var style = "label-success";
        if (count > 0) {
            style = "label-success";
        } else {
            style = "label-danger";
        }
        return "<span class='label label-sm " + style + "'>" + count + "</span>";
    }
};

/******* Run ******/
caryr.attchLogout($('#logout-btn'));
caryr.attchChangeLang($('a.language'), function (e) {
    $('#select-language').html(e.html());
});
//Prevent disable tabs
$(".disabled").click(function (e) {
    e.preventDefault();
    return false;
});